Date.prototype.yyyymmdd = function() {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
    var dd  = this.getDate().toString();
    return yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0]); // padding
};

App.register('Contributions', Contributions = {

    init: function() {
        this.setup();
    },
    
    setup: function() {
        var self = this;

        $("#filter_apply").click(function(e) {
            e.preventDefault();
            App.notify("contributions.history");
        });

        $("#clear_btn").click(function(e) {
            e.preventDefault();
            self.clear_filter();
            App.notify("contributions.history");
        });

        $("#history_content").delegate('ul.pagination li a','click',function(e){
            e.preventDefault();
            var href = $(this).attr('href');
            var page = href.slice(-1);//
            self.load_history(page);
        });

        App.listen('contributions.history', function() {
            self.load_history();
        });

        $("#filter_apply").click();


        $("#query_receipt_dt").mask("9999-99-99");

        self.bind_auto_complete($("#query_member_no"),$("#query_hidden_member_no"));

    },


    clear_filter:function(){
        $("#query_receipt_dt").val('');
        $("#query_receipt_no").val('');
        $("#query_member_no").val('');
        $("#query_hidden_member_no").val('');
        $("#query_contribution_type").val('0');
        $("#query_currency").val('0');
        $("#query_cheque_status").val('0');
    },


    load_history:function(page){
        var self = this;

        $("#history_content").html("<div class='wrapper-lg text-center'><h4>Loading Profile. Please wait ...</h4></div>");

        if(typeof page == "undefined"){
            page = 1;
        }

        //member validation if any
        var t = $("#query_member_no").val();
        t = t.trim();
        //Make sure the hidden member no is cleared if the member no is cleared
        if(t.length == 0){
            $("#query_hidden_member_no").val('');
        }

        if(t.length > 0){
            var h = $("#query_hidden_member_no").val();
            h = h.trim();
            if(h.length <1){
                $("#history_content").html("<div class='wrapper-lg text-center'><h4>Please type member number and choose from the dropdown options </h4></div>");
                alertify.error('Member No Error');
                return
            }
        }

        var params = {
            'page': page,
            'query_receipt_dt': $("#query_receipt_dt").val(),
            'query_receipt_no': $("#query_receipt_no").val(),
            'query_member_no': $("#query_hidden_member_no").val(),
            'query_contribution_type': $("#query_contribution_type").val(),
            'query_currency': $("#query_currency").val(),
            'query_cheque_no': $("#query_cheque_no").val(),
            'query_cheque_status': $("#query_cheque_status").val()
        };

        var url = $("#cheque_url").val() + "/paginate";

        $.ajax({
            url: url,
            data:params,
            dataType: 'json',
            type: 'post',
            success: function(res) {

                if(res.status == 'success'){
                    $("#history_content").html(res.render);
                    //self.renderImages(res);
                    //self.hide_loader();
                    //self.show_content();
                }
                else{
                    $("#history_content").html("<div class='wrapper-lg text-center'><h4>No Record Found</h4></div>");
                }
            },
            error: function(xhr) {
                alertify.error('Server Error');
                $("#history_content").html("<div class='wrapper-lg text-center'><h4>No Record Found</h4></div>");
                console.log(xhr.responseText);
            }
        });
    },


    bind_auto_complete:function(jquery_obj,jquery_hidden_obj){
        var self = this;

        jquery_obj.autocomplete({
            source: $("#contacts-autocomplete-url").val(),
            minLength: 2,
            select: function( event, ui ) {
                if ( ui.item ) {
                    //console.log(ui.item)
                    var hidden = jquery_hidden_obj;
                    hidden.val(ui.item.organization_member_id);
                }
            },
            create: function() {
                $(this).data('ui-autocomplete')._renderMenu = function( ul, items ) {
                    var that = this;

                    $.each(items, function( index, item ) {
                        var isPill = false;

                        $(".pillbox li").each(function() {
                            if( $(this).data('number') == item.number ) {
                                isPill = true;
                                return false;
                            }
                        });

                        if( !isPill ) {
                            that._renderItemData(ul, item);
                        }
                    });
                    $(ul).find("li:odd").addClass("odd");
                };

                $(this).data('ui-autocomplete')._renderItem = function( ul, item ) {
                    return $("<li>")
                        .append("<div class='name font-bold text-sm p-xs b-b bg-light'>" + item.label + "</div>").appendTo(ul);
                };

                $(this).data('ui-autocomplete')._resizeMenu = function() {
                    this.menu.element.outerWidth(300);
                };
            }
        });

    }
});


App.register("ContributionsEditor", ContributionsEditor = {

    init: function() {
        var self = this;

        $('#history_content').delegate('#collections_tbl_list tbody tr td i.edit-btn','click',function(){
            var parent_data_id = $(this).attr('parent-data-id');
            var tr = $("tr[data-contribution-id='" + parent_data_id + "']");
            self.process_row(tr);
        });

        $('#history_content').delegate('#collections_tbl_list tbody tr td i.delete-btn','click',function(){
            var parent_data_id = $(this).attr('parent-data-id');
            var tr = $("tr[data-contribution-id='" + parent_data_id + "']");
            self.delete_contribution(tr.attr('data-receipt-id'),tr.attr('data-contribution-id'));
        });

        $('#history_content').delegate('#collections_tbl_list tbody tr td i.cancel-btn','click',function(){
            var parent_data_id = $(this).attr('parent-data-id');
            var tr = $("tr[data-contribution-id='" + parent_data_id + "']");
            self.cancel_editing(tr);
        });

        $('#history_content').delegate('#collections_tbl_list tbody tr td i.save-btn','click',function(){
            var parent_data_id = $(this).attr('parent-data-id');
            var tr = $("tr[data-contribution-id='" + parent_data_id + "']");
            self.save_row(tr);
        });
    },


    delete_contribution:function(receipt_id,contribution_id){
        var self = this;
        alertify.confirm("Are you sure you want to delete this contribution record ?", function (e) {
            if (e) {
                self.show_row_loader(contribution_id,false);
                var url = $("#cheque_url").val()+'/delete';
                var params = {contribution_id: contribution_id};
                $.ajax({
                    url: url,
                    data: params,
                    type: 'post',
                    dataType: 'json',
                    success: function(response) {
                        self.show_row_loader(contribution_id,false,false);
                        if(response.status == 'success'){
                            $("tr[data-contribution-id='" + contribution_id + "']").hide('slow').remove();
                            alertify.success(response.message);
                        }
                        else{
                            alertify.error(response.message);
                        }
                    },
                    error: function(xhr) {
                        self.show_row_loader(contribution_id,false,false);
                        alertify.error("Failed to remove selected accounts. Please try again later");
                    }
                });
            } else {
                // user clicked "cancel"
            }
        });
    },



    show_row_loader:function(contribution_id,editing,state){
        if(typeof state == "undefined"){
            state = true;
        }
        if(state){
            $('#row-edit-btn_'+contribution_id).hide();
            $('#row-delete-btn_'+contribution_id).hide();
            $('#row-loader-btn_'+contribution_id).show();
            $('#row-save-btn_'+contribution_id).hide();
            $('#row-cancel-btn_'+contribution_id).hide();
        }
        else{
            $('#row-loader-btn_'+contribution_id).hide();
            if(editing){
                $('#row-save-btn_'+contribution_id).show();
                $('#row-cancel-btn_'+contribution_id).show();
            }
            else{
                $('#row-edit-btn_'+contribution_id).show();
                $('#row-delete-btn_'+contribution_id).show();
            }
        }
    },


    show_row_edit:function(contribution_id,state){
        if(typeof state == "undefined"){
            state = true;
        }
        if(state){
            $('#row-edit-btn_'+contribution_id).hide();
            $('#row-delete-btn_'+contribution_id).hide();
            $('#row-loader-btn_'+contribution_id).hide();
            $('#row-save-btn_'+contribution_id).show();
            $('#row-cancel-btn_'+contribution_id).show();
        }
        else{
            $('#row-save-btn_'+contribution_id).hide();
            $('#row-cancel-btn_'+contribution_id).hide();
            $('#row-loader-btn_'+contribution_id).hide();
            $('#row-edit-btn_'+contribution_id).show();
            $('#row-delete-btn_'+contribution_id).show();
        }
    },


    select_active_row:function(select_me){
        var self = this;

        $('#collections_tbl_list tbody tr.editing').each(function(){
            var me = $(this);
            if(me.hasClass('active') && (select_me.attr('data-id') != me.attr('data-id'))){//I was the last active row, validate and save me.
                self.process_row(me);
            }
            me.removeClass('active');
        });
        select_me.addClass('active');
    },


    process_row:function(tr){
        var self = this;
        //Check if there is any editing , then try save
        var tr_editing = $('#collections_tbl_list tbody tr.editing');
        if(tr_editing.length > 0){
            self.save_row(tr_editing,function(){
                self.add(tr);
            });
        }
        else{
            self.add(tr);
        }
    },


    add:function(tr){
        var self = this;

        var tr_id = tr.attr('data-contribution-id');

        tr.attr('class','editing').removeClass('saving').removeClass('row_error');


        //Payment Status
        var td = tr.find("td:nth-child(9)");
        var value = td.attr("data-cheque_status");
        var select = $('<select />').attr('class','input-sm form-control input-s-sm inline').addClass('row_cheque_status').attr('id','row_cheque_status_'+tr_id);
        var default_val = '';
        for(var x in cheque_statuses){
            var opt_data = cheque_statuses[x];
            var option = $('<option />').attr('value',x).html(opt_data);
            if(opt_data == value){
                default_val = opt_data.id;
            }
            select.append(option);
        }
        select.val(default_val);
        td.html('');
        td.append(select);

        //Save,Delete Button or Loader
        //var td = tr.find("td:nth-child(8)");
        self.show_row_edit(tr_id);

    },


    cancel_editing:function(tr){
        var self = this;

        var tr_id = tr.attr('data-contribution-id');

        tr.removeClass('editing').removeClass('saving').removeClass('row_error');

        //Cheque Status
        var td = tr.find("td:nth-child(9)");
        var value = td.attr("data-cheque_status");
        td.html(value);

        self.show_row_edit(tr_id,false);
    },



    animate_row_save:function(tr,editing,animate){
        var self = this;
        if(typeof animate == 'undefined'){
            animate = true;
        }

        var tr_id = tr.attr('data-contribution-id');

        var cheque_status_obj  = tr.find('td select#row_cheque_status_'+tr_id);

        if(animate){
            cheque_status_obj.attr('disabled','disabled').removeClass('field_error');
            self.show_row_loader(tr_id,editing,true);
        }
        else{
            cheque_status_obj.removeAttr('disabled').removeClass('field_error');
            self.show_row_loader(tr_id,editing,false);
        }

    },


    validate_row:function(tr){
        var self = this;

        var error_obj = [];


        if(error_obj.length > 0){
            var txt = '';
            for(var x in error_obj){
                var t = error_obj[x];
                txt = txt + t.msg +' <br />';
                t.obj.addClass('field_error');
            }
            alertify.error(txt);
            return false;
        }
        else{
            return true;
        }
    },


    save_row:function(tr,callback){
        var self = this;

        //Validate
        var res = self.validate_row(tr);
        if(res){
        }
        else{ //Validation error, so back to editing
            tr.removeClass('saving').addClass('editing');
            return;
        }

        var tr_id = tr.attr('data-contribution-id');
        var cheque_status = tr.find('td select#row_cheque_status_'+tr_id).val();

        //Animate Saving
        self.animate_row_save(tr,true);

        var data = {
            'contribution_id':tr_id,
            'receipt_id':tr.attr('data-receipt-id'),
            'cheque_status':cheque_status
        };
        var query = data;
        self.save(query,tr,callback);
    },

    save: function(data,tr,callback) {
        var self = this;

        var url = $("#cheque_url").val()+'/save';
        var params = 'data='+encodeURIComponent(JSON.stringify(data));

        $.ajax({
            url: url,
            data: params,
            type: 'post',
            dataType: 'json',
            success: function(res) {
                self.animate_row_save(tr,true,false);
                if( typeof res['status'] != "undefined" ) {
                    if( res['status'] == 'success' ) {
                        alertify.success(res['message']);
                        self.post_save(tr,res);
                        if(typeof callback == "function"){
                            callback();
                        }
                    }
                    else {
                        alertify.error(res['message']);
                    }
                }
                else {
                    alertify.error(JSON.stringify(res));
                }
            },
            error: function() {
                self.animate_row_save(tr,true,false);
                alertify.error("Failed to save member contribution.");
            }
        });
    },


    post_save:function(tr,data){
        var self = this;
        var tr_id = tr.attr('data-contribution-id');

        if( data['status'] == 'success' ) {
            var cheque_status_obj  = tr.find('td select#row_cheque_status_'+tr_id);
            var parent_td = cheque_status_obj.parent('td');
            var text  = cheque_status_obj.find("option:selected").text();
            var val  = cheque_status_obj.find("option:selected").val();
            parent_td.attr("data-cheque_status",val).html(text);
            cheque_status_obj.remove();

            self.show_row_edit(tr_id,false);
            tr.removeClass('saving').removeClass('editing').removeClass('row_error');
        }
        else{
            tr.removeClass('saving').addClass('editing').addClass('row_error');
            self.show_row_edit(tr_id,true);
            alertify.error(err);
        }
    }
});
